<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="68px">
            <el-form-item label="父属性" prop="parentId">
                <el-input v-model="queryParams.parentId" placeholder="请输入父属性" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="属性名称" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入属性名称" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['product:attribute:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll">展开/折叠</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-if="refreshTable" v-loading="loading" :data="attributeList" row-key="id"
            :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
            <!-- <el-table-column label="父属性" prop="parentId" /> -->
            <el-table-column label="属性名称" align="center" prop="name" />
            <el-table-column label="排序" align="center" prop="orderNum" />
            <el-table-column label="属性预览图" align="center" prop="previewImage" width="100">
                <template slot-scope="scope">
                    <image-preview :src="scope.row.previewImage" :width="50" :height="50" />
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['product:attribute:edit']">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-plus" @click="handleAdd(scope.row)"
                        v-hasPermi="['product:attribute:add']">新增</el-button>
                    <el-button v-if="scope.row.isSystem != 1" size="mini" type="text" icon="el-icon-delete"
                        @click="handleDelete(scope.row)" v-hasPermi="['product:attribute:remove']">删除</el-button>
                    <el-button v-if="scope.row.parentId === 1" size="mini" type="text" icon="el-icon-plus"
                        @click="handlePartsAdd(scope.row)">关联配件</el-button>
                    <!-- <el-button
            v-if="scope.row.parentId===8"
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleConfigAdd(scope.row)"
          >关联配置</el-button> -->
                </template>
            </el-table-column>
        </el-table>

        <!-- 添加或修改产品属性对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="150px">
                <el-form-item label="父属性" prop="parentId">
                    <treeselect v-model="form.parentId" :options="attributeOptions" :normalizer="normalizer"
                        placeholder="请选择父属性" />
                </el-form-item>
                <el-form-item label="属性名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入属性名称" clearable />
                </el-form-item>
                <el-form-item label="固定机位加宽(cm)" prop="name">
                    <el-input-number v-model="form.extraLength" placeholder="请输入固定机位增加宽度" clearable :precision="0"
                        controls-position="right" />
                </el-form-item>
                <el-form-item label="滑轨长度系数" prop="railLengthTimes">
                    <el-input-number v-model="form.railLengthTimes" clearable :precision="2" :step="0.1" :min="1"
                        placeholder="请输入滑轨长度系数" />
                </el-form-item>
                <el-form-item label="单位价格增加(㎡)" prop="extraPrice">
                    <el-input-number v-model="form.extraPrice" clearable :precision="2" :step="0.1" :min="0"
                        placeholder="" />
                </el-form-item>
                <el-form-item label="排序" prop="orderNum">
                    <el-input v-model="form.orderNum" placeholder="请输入排序" />
                </el-form-item>
                <el-form-item label="属性预览图" prop="previewImage">
                    <image-upload v-model="form.previewImage" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 添加或修改分类属性关联对话框 -->
        <el-dialog title="关联配件" :visible.sync="partsRelatedOpen" width="500px" append-to-body>
            <el-form ref="partsRelatedForm" :model="partsRelatedForm" :rules="partsRelatedRules" label-width="80px">
                <el-form-item label="可选配件" prop="optionIds">
                    <treeselect v-model="partsRelatedForm.optionIds" :options="partsOptions" :multiple="true"
                        :show-count="true" value-consists-of="ALL" placeholder="请选择可选配件" />
                    <!-- <el-select v-model="partsRelatedForm.optionIds" multiple filterable placeholder="请选择">
                <el-option
                v-for="item in partsOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
                </el-option>
            </el-select>         -->
                </el-form-item>
                <el-form-item label="必选配件" prop="requiredIds">
                    <treeselect v-model="partsRelatedForm.requiredIds" :options="partsOptions" :multiple="true"
                        :show-count="true" value-consists-of="ALL" placeholder="请选择必选配件" />
                    <!-- <el-select v-model="partsRelatedForm.requiredIds" multiple filterable placeholder="请选择">
                <el-option
                v-for="item in partsOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
                </el-option>
            </el-select> -->
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="partsRelatedSubmitForm">确 定</el-button>
                <el-button @click="partsRelatedCancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 添加或修改功能属性关联对话框 -->
        <el-dialog title="关联功能配置项" :visible.sync="configRelatedOpen" width="500px" append-to-body>
            <el-form ref="configRelatedForm" :model="configRelatedForm" :rules="configRelatedRules" label-width="80px">
                <el-form-item label="功能配件项" prop="optionIds">
                    <treeselect v-model="configRelatedForm.optionIds" :options="configOptions" :multiple="true"
                        :show-count="true" placeholder="请选择配置项" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="configRelatedSubmitForm">确 定</el-button>
                <el-button @click="configRelatedCancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listAttribute, getAttribute, delAttribute, addAttribute, updateAttribute, insertRelated, queryRelatedList } from "@/api/product/attribute";
import { listParts, getPartsOptions } from '@/api/product/parts';
import { queryConfigTree } from '@/api/product/config';
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
    name: "Attribute",
    components: {
        Treeselect
    },
    data () {
        return {
            // 遮罩层
            loading: true,
            // 显示搜索条件
            showSearch: true,
            // 产品属性表格数据
            attributeList: [],
            // 产品属性树选项
            attributeOptions: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 是否展开，默认全部展开
            isExpandAll: true,
            // 重新渲染表格状态
            refreshTable: true,
            // 查询参数
            queryParams: {
                parentId: null,
                name: null,
                orderNum: null,
                previewImage: null
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                parentId: [
                    { required: true, message: "父属性不能为空", trigger: "blur" }
                ],
                name: [
                    { required: true, message: "属性名称不能为空", trigger: "blur" }
                ],
            },


            //配件
            partsOptions: [],
            partsRelatedRules: {

            },
            partsRelatedOpen: false,
            partsRelatedForm: {
            },
            //功能配置
            configOptions: undefined,
            configRelatedRules: {},
            configRelatedOpen: false,
            configRelatedForm: {},



        };
    },
    created () {
        this.getList();
        this.getPartsOptions();
        //this.getConfigTree();
    },
    methods: {
        /** config start */
        getConfigTree () {
            queryConfigTree().then(response => {
                this.configOptions = response.data;
            })
        },
        resetConfigForm () {
            this.configRelatedForm = {
                attrId: null,
                type: 'config',
                optionIds: null
            }
            this.resetForm('configRelatedForm');
        },
        handleConfigAdd (rowData) {
            this.configRelatedForm.attrId = rowData.id;
            this.configRelatedForm.type = 'config';
            queryRelatedList(this.configRelatedForm).then(res => {
                const optionIds = [];
                res.data.forEach(it => {
                    optionIds.push(it.relatedId);
                });
                this.configRelatedForm.optionIds = optionIds;

            })
            this.configRelatedOpen = true;

        },
        configRelatedCancel () {
            this.resetConfigForm();
            this.configRelatedOpen = false;
        },
        configRelatedSubmitForm () {
            this.$refs["configRelatedForm"].validate(valid => {
                if (valid) {

                    insertRelated(this.configRelatedForm).then(response => {
                        this.$modal.msgSuccess("保存成功");
                        this.resetConfigForm();
                        this.configRelatedOpen = false;
                    });
                }
            });
        },
        /** config end */
        /** parts start*/
        resetPartsForm () {
            this.partsRelatedForm = {
                attrId: null,
                type: 'parts',
                requiredIds: null,
                optionIds: null
            }
            this.resetForm('partsRelatedForm');
        },
        getPartsOptions () {
            getPartsOptions().then(res => {
                this.partsOptions = res.data;
            })
            // listParts({
            //     pageNum:1,
            //     pageSize:100
            // }).then(res=>{
            //     this.partsOptions=res.rows.map(it=>{
            //         return {
            //             label:it.partName+"(+"+it.price+"元)",
            //             value:it.id
            //         }
            //     })
            //     console.log(this.partsOptions);
            // })
        },
        handlePartsAdd (rowData) {
            this.partsRelatedForm.attrId = rowData.id;
            this.partsRelatedForm.type = 'parts';
            queryRelatedList(this.partsRelatedForm).then(res => {
                console.log('res', res);
                const requiredIds = [];
                const optionIds = [];
                res.data.forEach(it => {
                    if (it.isRequired === 1) {
                        requiredIds.push(it.relatedId);
                    } else {
                        optionIds.push(it.relatedId);
                    }
                });
                //console.log(requiredIds,optionIds);
                this.partsRelatedForm.requiredIds = requiredIds;
                this.partsRelatedForm.optionIds = optionIds;

            })
            this.partsRelatedOpen = true;

        },
        partsRelatedCancel () {
            this.resetPartsForm();
            this.partsRelatedOpen = false;
        },
        partsRelatedSubmitForm () {
            this.$refs["partsRelatedForm"].validate(valid => {
                if (valid) {
                    insertRelated(this.partsRelatedForm).then(response => {
                        this.$modal.msgSuccess("保存成功");
                        this.resetPartsForm();
                        this.partsRelatedOpen = false;
                    });
                }
            });
        },
        /** parts end */
        /** 查询产品属性列表 */
        getList () {
            this.loading = true;
            listAttribute(this.queryParams).then(response => {
                this.attributeList = this.handleTree(response.data, "id", "parentId");
                this.loading = false;
            });
        },
        /** 转换产品属性数据结构 */
        normalizer (node) {
            if (node.children && !node.children.length) {
                delete node.children;
            }
            return {
                id: node.id,
                label: node.name,
                children: node.children
            };
        },
        /** 查询产品属性下拉树结构 */
        getTreeselect () {
            listAttribute().then(response => {
                this.attributeOptions = [];
                const data = { id: 0, name: '顶级节点', children: [] };
                data.children = this.handleTree(response.data, "id", "parentId");
                this.attributeOptions.push(data);
            });
        },
        // 取消按钮
        cancel () {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset () {
            this.form = {
                id: null,
                parentId: null,
                name: null,
                extraLength: null,
                railLengthTimes: null,
                extraPrice: 0,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                previewImage: null
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery () {
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery () {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 新增按钮操作 */
        handleAdd (row) {
            this.reset();
            this.getTreeselect();
            if (row != null && row.id) {
                this.form.parentId = row.id;
            } else {
                this.form.parentId = 0;
            }
            this.open = true;
            this.title = "添加产品属性";
        },
        /** 展开/折叠操作 */
        toggleExpandAll () {
            this.refreshTable = false;
            this.isExpandAll = !this.isExpandAll;
            this.$nextTick(() => {
                this.refreshTable = true;
            });
        },
        /** 修改按钮操作 */
        handleUpdate (row) {
            this.reset();
            this.getTreeselect();
            if (row != null) {
                this.form.parentId = row.parentId;
            }
            getAttribute(row.id).then(response => {
                this.form = response.data;
                this.open = true;
                this.title = "修改产品属性";
            });
        },
        /** 提交按钮 */
        submitForm () {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.id != null) {
                        updateAttribute(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addAttribute(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete (row) {
            this.$modal.confirm('是否确认删除产品属性编号为"' + row.id + '"的数据项？').then(function () {
                return delAttribute(row.id);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        }
    }
}
</script>